package com.hugh.blog_cache.service.impl;

import com.hugh.blog_cache.dao.model.TArticle;
import com.hugh.blog_cache.dao.model.TArticleExample;
import com.hugh.blog_cache.entity.RequestEntity;
import com.hugh.blog_cache.entity.ResponseEntity;
import com.hugh.blog_cache.dao.mapper.TArticleMapper;
import com.hugh.blog_cache.entity.TArticleEntity;
import com.hugh.blog_cache.service.ArticleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @Author: Hugh
 * @Date: 2020/5/24
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private TArticleMapper tArticleMapper;

    @Override
    @Cacheable(cacheNames = "comment",unless = "#result==null", key = "#requestEntity.pageNum")
    public ResponseEntity queryAllArticlesByCondition(RequestEntity requestEntity) {

        Integer pageSize = 10;
        Integer pageNum = 1;
        if(Objects.nonNull(requestEntity) && Objects.nonNull(requestEntity.getPageNum()) && Objects.nonNull(requestEntity.getPageSize())){
            pageSize = requestEntity.getPageSize();
            pageNum = requestEntity.getPageNum();
        }
        TArticleExample example = new TArticleExample();
        example.createCriteria().andIdGreaterThan(0);
        long l = tArticleMapper.countByExample(example);
        ResponseEntity responseEntity = ResponseEntity.builder().count((int)l).build();
        if(l<=0) {
            responseEntity.setArticles(Collections.emptyList());
            return responseEntity;
        }
        List<TArticleEntity> articles = new ArrayList<>((int)l);
        example.setSize(pageSize);
        example.setOffset(pageSize * (pageNum - 1));
        List<TArticle> tArticles = tArticleMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(tArticles)){
            for (TArticle tArticle : tArticles) {
                TArticleEntity resEntity = new TArticleEntity();
                BeanUtils.copyProperties(tArticle, resEntity);
                articles.add(resEntity);
            }
        }
        responseEntity.setArticles(articles);
        return responseEntity;
    }
}
